<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {
            height: 1000px;
            width: 1000px;
        }

        body {
            height: 5000px;
        }

        div {
            height: 1000px;
        }
    </style>
</head>
<body>
    <div>
        <img data-src="./imgs/apple.png" alt="x" id="1">
    </div>
    <div>
        <img data-src="./imgs/lemon.png" alt="x" id="2">
    </div>
    <div>
        <img data-src="./imgs/orange.png" alt="x" id="3">
    </div>
    <div>
        <img data-src="./imgs/apple.png" alt="x" id="4">
    </div>
    <div>
        <img data-src="./imgs/lemon.png" alt="x" id="5">
    </div>
    <script>
        /**
         * 文档参考地址 http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html
        */
        //父元素必须有高度值(注意)
        let imgs = document.querySelectorAll('img');
        let observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting === true) {
                    console.log(entries);
                    entries[0].target.src = entries[0].target.dataset.src  // 替换src
                    observer.unobserve(entries[0].target)  // 停止观察当前元素 避免不可见时候再次调用callback函数
                }
            })
        },
            {
                threshold: 0.2
            })

        imgs.forEach((e) => {
            observer.observe(e);
        })
    </script>
</body>
</html>